package com.rock.sys.intercept;

import com.eova.aop.AopContext;
import com.eova.common.utils.EncryptUtil;
import com.eova.model.Role;
import com.eova.model.User;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.rock.sys.config.RockConst;
import com.rock.sys.global.RockMetaIntercept;
import com.rock.sys.model.TSTenant;
import com.rock.sys.model.TUser;

public class TenantIntercept extends RockMetaIntercept {

	/**
     * 新增后置任务(事务内)
     * <pre>
     * ac.record 当前操作数据
     * -------------
     * 用法：级联新增，需在同事务内完成
     * int id = ac.record.getInt("id");// 获取当前对象主键值，进行级联新增
     * </pre>
     */
	@Override
    public String addAfter(AopContext ac) throws Exception {
		
		//获取虚拟字段值
		String name = ac.record.getStr("v_user_name");
		String login_name = ac.record.getStr("v_user_login");
		String login_pwd = ac.record.getStr("v_user_password");

        //设置系统用户的角色，便于通过元数据统一控制数据访问权限
        Role role = Role.dao.findFirst("select * from eova_role where name=?", RockConst.TENANT_ADMIN_ROLE);
        
        if(role == null) {
        	return "新增租户失败，未找到租户管理员专属角色";
        }

		//业务用户
		TUser tuser = new TUser();
		//租户
		TSTenant tt = new TSTenant();

		//业务用户信息设置
		tuser.setLoginId(login_name);
		tuser.setNickname(name);
		tuser.setInfo("来源-新增租户同步加管理用户");
		tuser.setStatus(1);//状态设置为正常，否则无法登陆后台
		tuser.setRid(role.getInt("id"));
		tuser.setRids(role.getStr("id"));
        tuser.setTenantId(ac.record.getInt("id"));
        tuser.setAvatar(ac.record.getStr("logo"));
		tuser.save();
		Integer tuserId = tuser.getId();

		//系统用户信息设置
		User lUser = new User();
		lUser.set("id", tuserId);
		lUser.set("login_id", tuser.getLoginId());
		lUser.set("login_pwd", EncryptUtil.getSM32(login_pwd));
		lUser.set("rid", role.get("id"));
		lUser.set("rids", role.get("id"));
		lUser.save();

		//更新租户的管理员用户信息
		Record t = new Record();
		t.set("id", ac.record.getInt("id"));
		t.set("user_id", tuser.getId());
		Db.update("t_s_tenant", t);
		
        return null;
    }
}
